<template>
  <div>
    <category></category>
    <el-card style="margin: 0px 15px">
      <div class="spuInfo" v-if="scene == 1">
        <el-button
          type="primary"
          icon="Plus"
          @click="addSpuInfo"
          :disabled="!categoryStore.c3Id"
          >添加SPU</el-button
        >
        <el-table
          border
          style="width: 100%; margin: 15px 0"
          :data="spuListInfo"
        >
          <el-table-column prop="id" label="序号" width="120" align="center" />
          <el-table-column prop="spuName" label="SPU名称" align="center" />
          <el-table-column
            prop="description"
            label="SPU描述"
            align="center"
            show-overflow-tooltip
          />
          <el-table-column label="操作" align="center">
            <template #="{ row, $index }">
              <el-button
                icon="Plus"
                size="small"
                type="primary"
                @click="addSkuItem(row.id)"
              ></el-button>
              <el-button
                icon="Edit"
                size="small"
                type="warning"
                @click="editSpuInfo(row.id)"
              ></el-button>
              <el-button
                icon="InfoFilled"
                size="small"
                type="info"
                @click="showSkuInfoList(row.id)"
              ></el-button>
              <el-button
                icon="Delete"
                size="small"
                type="danger"
                @click="delSpu(row.id)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[3, 5, 7]"
          :background="true"
          layout=" prev, pager, next, jumper,->, sizes,total"
          :total="totalPage"
          @current-change="getSpuInfo"
          @size-change="updateSpuInfo"
        />
      </div>
      <div v-if="scene === 2">
        <el-form ref="spuInfoRef" :model="spuInfo">
          <el-form-item label="SPU名称" prop="spuName" label-width="100px">
            <el-input style="width: 150px" v-model="spuInfo.spuName"></el-input>
          </el-form-item>
          <el-form-item label="SPU品牌" prop="spuName" label-width="100px">
            <el-input style="width: 150px" v-model="spuInfo.spuName"></el-input>
          </el-form-item>
          <el-form-item label="SPU描述" prop="description" label-width="100px">
            <el-input v-model="spuInfo.description" type="textarea"></el-input>
          </el-form-item>
          <el-form-item label="SPU照片" prop="spuName" label-width="100px">
            <el-upload
              v-model:file-list="spuInfo.imgFileList"
              action="/api/admin/product/fileUpload"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :on-success="handleUploadSuccess"
              :before-upload="beforeUpload"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>
            <el-dialog v-model="dialogVisible">
              <img
                w-full
                :src="dialogImageUrl"
                alt="Preview Image"
                style="width: 100%"
              />
            </el-dialog>
          </el-form-item>
          <el-form-item
            label="SPU销售属性"
            prop="spuSaleAttrList"
            label-width="100px"
          >
            <el-select
              style="width: 200px; margin-right: 7px"
              v-model="selectedAttr"
              :placeholder="
                canAddAttrList.length > 0
                  ? `还有${canAddAttrList.length}种属性可以选择`
                  : '空'
              "
            >
              <el-option
                v-for="attr in canAddAttrList"
                :key="attr.id"
                :label="attr.name"
                :value="attr.id"
              ></el-option>
            </el-select>
            <el-button
              icon="Plus"
              type="primary"
              @click="addAttrBySelect"
              :disabled="canAddAttrList.length == 0"
              >添加属性值</el-button
            >
            <el-table
              border
              style="width: 100%; margin-top: 15px"
              :data="spuInfo.spuSaleAttrList"
            >
              <el-table-column
                type="index"
                label="序号"
                width="120"
                align="center"
              />
              <el-table-column
                label="属性名"
                align="center"
                prop="saleAttrName"
              >
              </el-table-column>
              <el-table-column label="属性值" align="center">
                <template #="{ row, $index }">
                  <el-tag
                    style="margin-right: 5px"
                    v-for="(attr, idx) in row.spuSaleAttrValueList"
                    closable
                    @close="delSaleAttrValue($index, idx)"
                    >{{ attr.saleAttrValueName }}
                  </el-tag>
                  <el-input
                    style="width: 100px"
                    size="small"
                    v-if="row.flag"
                    :ref="(vc:any)=>inputArr[$index]=(vc)"
                    @keydown.enter="(event:any) => event.target.blur()"
                    @blur="addSaleAttrValue($index)"
                    v-model="saleAttrValue"
                  ></el-input>
                  <el-button
                    icon="Plus"
                    v-else
                    @click="showInput($index)"
                    size="small"
                  ></el-button>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center">
                <template #="{ row, $index }">
                  <el-button
                    icon="Delete"
                    size="small"
                    type="danger"
                    @click="delAttr(row, $index)"
                  ></el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
          <div>
            <el-button type="primary" @click="saveSpuInfo">保存</el-button>
            <el-button @click="cancelEditSpuInfo">取消</el-button>
          </div>
        </el-form>
      </div>
      <div v-if="scene === 3">
        <SkuForm @change-scene="handleChangeScene" :spu-id="spuId"></SkuForm>
      </div>
    </el-card>
    <el-dialog v-model="skuDialogVisible" style="width: 550px">
      <el-table :data="skuInfoList">
        <el-table-column
          prop="skuName"
          label="SKU名称"
          width="120"
          align="center"
        />
        <el-table-column prop="price" label="价格" width="120" align="center" />
        <el-table-column
          prop="weight"
          label="SKU重量"
          width="120"
          align="center"
        />
        <el-table-column label="SKU图片" width="140" align="center">
          <template #="{ row, $index }">
            <img
              :src="row.skuDefaultImg"
              style="width: 100px; height: 100px; background-size: cover"
            />
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { nextTick, onMounted, reactive, ref, watch } from "vue";
import { startLoading, endLoading } from "../../../utils/loading";
import { ElMessage, type UploadProps, type UploadUserFile } from "element-plus";
import useCategoryStore from "../../../store/modules/category";
import {
  reqBaseAttr,
  reqDelSpu,
  reqSaveSpuInfo,
  reqSpuInfo,
  reqSpuInfoById,
  reqUpdateSpuInfo,
} from "../../../api/product/spu";
import {
  SpuInfoResponseForm,
  SpuInfoDataForm,
} from "../../../api/product/spu/type";
import confirm from "../../../utils/confirm";
import SkuForm from "./skuForm.vue";
import { reqFindSkuBySpuId } from "../../../api/product/sku";
const categoryStore = useCategoryStore();
const currentPage = ref(1);
const pageSize = ref(3);
const totalPage = ref(100);
const spuInfoVisible = ref(true);
const scene = ref(1);
const spuListInfo = ref([]);
const allAttr = ref([]);
const canAddAttrList = ref([]);
const selectedAttr = ref();
const saleAttrValueInput = ref(false);
const saleAttrValue = ref("");
const skuDialogVisible = ref<boolean>(false);
const saleAttrValueInputElement = ref();
const inputArr = ref<any>([]);
const spuId = ref<any>("");
const skuInfoList = ref([]);
let spuInfo = reactive<SpuInfoDataForm>({
  imgFileList: [],
  spuName: "",
  description: "",
  spuImageList: [],
  spuSaleAttrList: [],
  category3Id: "",
});
// 新添加的图片
let newImgUploadList = <any>[];
// 删除的图片
let newDelImgList = <any>[];
// 文件上传展示的列表
onMounted(async () => {
  let result = await reqBaseAttr();
  // result.data.forEach((item: any) => {
  //   allAttr.value.push(item.name);
  // });
  console.log(scene.value);
  categoryStore.isDisabled = false;
  allAttr.value = result.data;
  console.log(allAttr.value);
});
const fileList = ref<UploadUserFile[]>([]);
const getSpuInfo = async () => {
  let result = await reqSpuInfo(
    currentPage.value,
    pageSize.value,
    categoryStore.c3Id
  );
  // console.log(result.data);
  spuListInfo.value = result.data.records;
  totalPage.value = result.data.total;
};
const updateSpuInfo = () => {
  currentPage.value = 1;
  getSpuInfo();
};
watch(
  () => categoryStore.c3Id,
  async () => {
    // console.log(categoryStore.c3Id !== "");
    if (categoryStore.c3Id !== "") {
      getSpuInfo();

      // console.log(attrData.value);
    } else {
    }
  }
);

// 添加SPU
const addSpuInfo = () => {
  // 不能再切换分类
  categoryStore.isDisabled = true;
  spuInfoVisible.value = false;
  scene.value = 2;
  spuInfo = reactive<SpuInfoDataForm>({
    imgFileList: [],
    spuName: "",
    description: "",
    spuImageList: [],
    spuSaleAttrList: [],
    category3Id: "",
  });
  newImgUploadList = [];
  newDelImgList = [];
  canAddAttrList.value = allAttr.value;
  spuInfo.imgFileList = [];
  selectedAttr.value = "";
  spuInfo.category3Id = categoryStore.c3Id;
};
// 编辑spu
const editSpuInfo = async (spuId: number) => {
  // 不能再切换分类
  categoryStore.isDisabled = true;
  // 新添加的和新删除的都要先删除掉
  newImgUploadList = [];
  newDelImgList = [];
  spuInfo.imgFileList = [];
  selectedAttr.value = "";
  canAddAttrList.value = [];
  let result = await reqSpuInfoById(spuId);
  console.log(result);
  Object.assign(spuInfo, result.data);
  // console.log(spuInfo);
  // 手机已有图片到另一个列表，做相应的处理
  spuInfo.spuImageList.forEach((imgInfo: any) => {
    spuInfo.imgFileList.push({ name: imgInfo.imgName, url: imgInfo.imgUrl });
  });
  // 查看还有哪些属性可以添加
  allAttr.value.forEach((baseAttr) => {
    if (
      !spuInfo.spuSaleAttrList.find(
        (attr) => attr.baseSaleAttrId === baseAttr.id
      )
    ) {
      canAddAttrList.value.push(baseAttr);
    }
  });
  // console.log(canAddAttrList.value);
  spuInfoVisible.value = false;
  scene.value = 2;
};

const delSpu = (spuId: number) => {
  confirm("你确定要删除吗？", async () => {
    startLoading();
    let result = await reqDelSpu(spuId);
    if (!result) {
      ElMessage.error("删除失败");
      endLoading();
    } else {
      setTimeout(() => {
        getSpuInfo();
        endLoading();
        ElMessage.success("删除成功");
      }, 3000);
    }
  });
};

const saveSpuInfo = async () => {
  // 需要判断是保存还是更新
  spuInfoVisible.value = true;
  scene.value = 1;
  spuInfo.spuImageList = [...spuInfo.spuImageList, ...newImgUploadList];
  // console.log(newDelImgList);
  newDelImgList.forEach((spuName: string) => {
    spuInfo.spuImageList = spuInfo.spuImageList.filter(
      (item: any) => item.imgName != spuName
    );
  });
  console.log(spuInfo);
  startLoading();
  if (spuInfo.id) {
    let result = await reqUpdateSpuInfo(spuInfo);
  } else {
    let result = await reqSaveSpuInfo(spuInfo);
  }
  // 可以切换分类
  categoryStore.isDisabled = false;
  getSpuInfo();
  nextTick(() => {
    endLoading();
  });
};

const cancelEditSpuInfo = () => {
  spuInfoVisible.value = true;
  scene.value = 1;
  // 可以切换分类
  categoryStore.isDisabled = false;
};
// 查看spu图片/删除spu图片
const dialogImageUrl = ref("");
const dialogVisible = ref(false);

const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  // console.log(uploadFile, uploadFiles);
  // nextTick(() => {
  //   console.log(spuInfo.imgFileList);
  // });
  newDelImgList.push(uploadFile.name);
};

const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};

// 照片上传前的处理以及，上传成功后的处理

const handleUploadSuccess = (data: any) => {
  let length = spuInfo.imgFileList.length;
  newImgUploadList.push({
    imgName: spuInfo.imgFileList[length - 1].name,

    imgUrl: data.data,
    spuId: spuInfo.id,
  });
  // console.log(spuInfo.imgFileList);
};
const beforeUpload = (data: any) => {};
const addAttrBySelect = () => {
  const idx = selectedAttr.value - 1;
  spuInfo.spuSaleAttrList.push({
    saleAttrName: allAttr.value[idx].name,
    spuSaleAttrValueList: [],
    baseSaleAttrId: allAttr.value[idx].id,
    flag: false,
  });
  canAddAttrList.value = canAddAttrList.value.filter(
    (item: any) => item.id != selectedAttr.value
  );
  selectedAttr.value = "";
  console.log(canAddAttrList.value);
};

const showInput = (idx: number) => {
  saleAttrValue.value = "";
  spuInfo.spuSaleAttrList[idx].flag = true;
  nextTick(() => {
    inputArr.value[idx].focus();
  });
};

const delAttr = (data: any, idx: number) => {
  console.log(data);
  spuInfo.spuSaleAttrList.splice(idx, 1);
  canAddAttrList.value.push({
    id: data.baseSaleAttrId,
    name: data.saleAttrName,
  });
};

const addSaleAttrValue = (id: number) => {
  const idx = id;
  if (saleAttrValue.value.trim().length > 0) {
    // 判断是否重复
    if (
      spuInfo.spuSaleAttrList[idx].spuSaleAttrValueList.find(
        (item: any) => item.saleAttrValueName === saleAttrValue.value.trim()
      )
    ) {
      ElMessage.error("属性值不能重复");
      inputArr.value[idx].focus();
      saleAttrValue.value = "";
    } else {
      spuInfo.spuSaleAttrList[idx].spuSaleAttrValueList.push({
        saleAttrValueName: saleAttrValue.value.trim(),
        spuId: spuInfo.id,
        saleAttrName: spuInfo.spuSaleAttrList[idx].saleAttrName,
        baseSaleAttrId: spuInfo.spuSaleAttrList[idx].baseSaleAttrId,
      });
      spuInfo.spuSaleAttrList[idx].flag = false;
    }
  } else {
    ElMessage.error("属性值不能为空");
    spuInfo.spuSaleAttrList[idx].flag = false;
  }
};

const delSaleAttrValue = (baseId: number, idx: number) => {
  const baseIdx = baseId;
  spuInfo.spuSaleAttrList[baseIdx].spuSaleAttrValueList.splice(idx, 1);
};

const addSkuItem = (id: number) => {
  scene.value = 3;
  spuId.value = id;
};

const handleChangeScene = (sceneId: number) => {
  scene.value = sceneId;
};

const showSkuInfoList = async (id: number) => {
  let result = await reqFindSkuBySpuId(id);
  skuInfoList.value = result.data;
  skuDialogVisible.value = true;
  console.log(skuInfoList.value);
};
</script>

<style lang="scss" scoped></style>
